import { get, add, remove,updateById } from "../../utils/db"
Page({
  data: {
    list: [],      //菜谱分类列表
    addTag: false,     //false 添加输入框隐藏；true 显示
    updateTag: false,    //false 更改输入框隐藏；true 显示
    name: "",        //菜谱分类名称
  },
  async onLoad() {
    this.getList()
  },
  //获取type列表
  async getList() {
    let openid = wx.getStorageSync('openid')
    let result = await get({ collection: "type", where: { _openid: openid } }).catch(err => {
      console.log(err)
    })
    // console.log(result)
    this.setData({
      list: result.data
    })
  },
  //点击加号，显示添加输入框
  showAdd() {
    this.setData({
      addTag: true
    })
  },
  async add() {
    //添加数据库
    await add({ collection: "type", data: { name: this.data.name } }).catch(err => {
      console.error(err)
    })
    
      this.getList()
      this.setData({
        addTag:false,
        name:""
      })

  },
  //删除数据
  del(e) {
    //弹出框
    wx.showModal({
      title: '温馨提示',
      content: "您确认要删除吗？",
      success: async res => {
        // console.log(res)
        if (res.confirm) {
          let id = e.currentTarget.id;    //获取到菜谱分类的id
          await remove({ collection: "type", where: { _id: id } }).catch(err => {
            console.log(err)
          })

          this.getList()
        }
      }
    })

    // return;

  },
  //显示修改框
  showUpdate(e){
    let name=e.currentTarget.dataset.name;
    let id=e.currentTarget.dataset.id;
    
    this.setData({
      updateTag:true,
      name,
      id
    })
  },
  //执行修改
  async update(){
    let id=this.data.id;    //修改的id
    let name=this.data.name;
    let result =await updateById({collection:"type",id:id,data:{name}}).catch(err=>{
      console.error(err)
    })
    // console.log(result)
    this.getList()
    this.setData({
      updateTag:false,
      name:""
    })
  }
})